package Model.DAO.uselessDao;

import Model.Entity.Admins;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AdminDao {
    private static InitialContext context = null;
    private DataSource dataSource = null;
    public AdminDao()
    {
        try
        {
            if (context == null)
            {
                context = new InitialContext();
            }
            dataSource = (DataSource)context.lookup("java:comp/env/jdbc/mysql");
        } catch (NamingException ex) {
            Logger.getLogger(BookDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    public boolean changePwd(Admins admin){
        Connection conn = null;        try{
            conn = dataSource.getConnection();
            PreparedStatement pre = conn.prepareStatement("UPDATE admins SET pwd='"+ admin.getPwd()+"'"+" WHERE name='"+ admin.getName() +"'");
            int rst = pre.executeUpdate();
            conn.close();
            if(rst!=0)
                return true;
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    public int searchAdmin(Admins admin)
    {
        int flag=0;
        Connection conn = null;
        try{
            conn = dataSource.getConnection();
            PreparedStatement pre = conn.prepareStatement("SELECT * FROM admins WHERE name='"+ admin.getName() +"'");
            ResultSet rst = pre.executeQuery();
            if(rst.next())
            {
                String pwd = admin.getPwd();
                if(pwd.equals(rst.getString(3))){
                    flag=1;
                }else {
                    flag=0;
                }
            }
        }
        catch(SQLException e)
        {
            flag=0;
            e.printStackTrace();
        }
        finally{
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return flag;
        }
    }
}
